﻿Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text

Public Module IniFile

    ' 从kernel32.dll导入GetPrivateProfileString函数用于读取INI文件
    <DllImport("kernel32.dll", CharSet:=CharSet.Unicode)>
    Private Function GetPrivateProfileString(ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As StringBuilder, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    End Function

    ' 从kernel32.dll导入WritePrivateProfileString函数用于写入INI文件
    <DllImport("kernel32.dll", CharSet:=CharSet.Unicode)>
    Private Function WritePrivateProfileString(ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Boolean
    End Function

    ' 引入Windows API函数GetPrivateProfileSectionNames
    <DllImport("kernel32.dll", CharSet:=CharSet.Unicode)>
    Private Function GetPrivateProfileSectionNames(ByVal lpszReturnBuffer As System.Text.StringBuilder, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    End Function

    ' 读取INI文件中指定节和键的值
    Function ReadIniValue(ByVal iniFilePath As String, ByVal section As String, ByVal key As String) As String
        Dim buffer As New StringBuilder(10240)
        GetPrivateProfileString(section, key, "", buffer, buffer.Capacity, iniFilePath)
        Return buffer.ToString()
    End Function

    ' 向INI文件中指定节和键写入值
    Sub WriteIniValue(ByVal iniFilePath As String, ByVal section As String, ByVal key As String, ByVal value As String)
        WritePrivateProfileString(section, key, value, iniFilePath)
    End Sub

    Function GetSections(ByVal iniFilePath As String) As ArrayList

        Dim sectionNameList As New ArrayList
        Dim sr As New StreamReader(iniFilePath)

        Dim strLine As String
        While Not sr.EndOfStream

            strLine = sr.ReadLine()
            strLine = Trim(strLine)
            If Not strLine.StartsWith("#") Then

                If Trim(strLine.StartsWith("[")) Then
                    sectionNameList.Add(strLine.Substring(1, strLine.IndexOf("]") - 1))

                End If

            End If

        End While
        sr.Close()
        GetSections = sectionNameList
    End Function




End Module
